import React from 'react';
import './Saydetail.css';
import { Toast } from 'antd-mobile';
import Topbar from '../../components/Topbar/Topbar';
import Saycomment from '../../components/Saycomment/Saycomment';
import moment from 'moment';
import axios from 'axios'; 

class SayDetail extends React.Component {  
    constructor(props){          
        super(props);        
        this.state = {
            //动态信息
            userid:this.props.location.state.userid,
            time:this.props.location.state.time,
            title:this.props.location.state.title,
            content:this.props.location.state.content,
            imgsrc:this.props.location.state.imgsrc,
            sayid:this.props.location.state.sayid,
            commentnum:this.props.location.state.commentnum,
            likenum:this.props.location.state.likenum,
            //动态下的评论
            commentList:[],
            //页面动态效果
            selectcomment:'none',
            selectlike:'no',
            //是否显示图片
            imgExist:this.props.location.state.imgsrc==null? 'none':'block',
            commentContent:'',

            //获取本地中使用用户的id
            id:localStorage.getItem('userid'),
        }  
    } 

    async componentDidMount() {
        //获取发布动态用户的头像和昵称
        fetch(`https://www.prebeauty.work/user/${this.state.userid}`,{
        method:'GET',
        headers:{
            'content-type': 'application/json'
        }
        }).then((res)=>{
            if(res.status===200){
                res.json().then( (data)=> {
                    this.setState({
                        confimg:data[0].image,
                        nickname:data[0].name,
                    })
                    console.log(this.state.confimg)
                })
            }else {
                alert("出现一个问题");
            }
        })
        //获得动态下的评论
        await axios.get('https://www.prebeauty.work/saycomment/'+this.state.sayid)
    　　　.then((res) => {
            this.setState({
                commentList:res.data
            })
            console.log(this.state.commentList)
    　　　})
         .catch((err) => {
         　　console.log(err);
         })

        //获取用户是否点赞
        await fetch(`https://www.prebeauty.work/saylike/${this.state.userid}&${this.state.sayid}`, {
            method: 'GET',
            headers: {
                'content-type': 'application/json'
            }
            }).then((res) => {
            if (res.status === 200) {
                res.json().then((data) => {
                    this.setState({
                        selectlike: data[0] ? 'yes' : 'no'
                    })
                })
            } else {
                console.log('erro')
            }
            })
    }

    /*显示评论发布的窗口 */
    showSayComment(){
        if(this.state.selectcomment === 'none'){
            this.setState({
                selectcomment:'block'
            })
        }else if(this.state.selectcomment === 'block'){
            this.setState({
                selectcomment:'none'
            })
        }
    } 

    /*点赞,取消点赞*/
    async changeLikeicon(){
        //点赞
        if(this.state.selectlike==='no'){  
            this.state.likenum++
            this.setState({
                selectlike:'yes',
            })
            Toast.success('已点赞',1);  
            //向点赞表中添加 
            const likeparam={
                userid:this.state.userid,
                sayid:this.state.sayid,
            }
            await fetch('https://www.prebeauty.work/saylike', {
                method: 'POST',
                body: JSON.stringify(likeparam),
                headers: {
                    'Content-Type': 'application/json'
                },
            })
            .then((res) => res.json() )
            .then((res) => {
                console.log(res);     
            })
             //向动态表中likenum+1
            const likenumParam={
                likenum:this.state.likenum
            }
            await fetch(`https://www.prebeauty.work/saying/${this.state.sayid}`, {
                method: 'PUT',
                body: JSON.stringify(likenumParam),
                headers: {
                    'Content-Type': 'application/json'
                },
            })
            .then((res) => res.json() )
            .then((res) => {
                console.log(res);
            })

        //取消点赞
        }else if(this.state.selectlike==='yes'){
            this.setState({
                selectlike:'no'
            })   
            this.state.likenum--
            Toast.fail('取消点赞',1);   
        //删除点赞表中的信息
        await fetch(`https://www.prebeauty.work/saylike/${this.state.userid}&${this.state.sayid}`,{
            method:'DELETE',
            headers:{
                'content-type': 'application/json'
            }
        }).then((res)=>{
            if(res.status===200){
                res.json().then((data)=> {
                    console.log('取消点赞！')
                })
            }else {
                console.log('erro')
            }
        })
        //动态表中的likesnum-1
        const likeparam={
            likenum:this.state.likenum
        }
        fetch(`https://www.prebeauty.work/saying/${this.state.sayid}`,{
            method:'PUT',
            body:JSON.stringify(likeparam),
            headers:{
                'content-type': 'application/json'
            }
        }).then((res)=>{
            if(res.status===200){
                res.json().then((data)=> {
                    console.log('取消点赞！')
                })
            }else {
                console.log('erro')
            }
        })
        }
    }

    /*发布评论*/
    async uploadcomment(){
        //向评论表中添加评论
        var timestamp=new Date().getTime()
        const commentparam = {
            userid:this.state.id,
            sayid:this.state.sayid,
            likenum:0,
            content:this.state.commentContent,
            time:timestamp
        }
        await fetch('https://www.prebeauty.work/saycomment', {
            method: 'POST',
            body: JSON.stringify(commentparam),
            headers: {
                'Content-Type': 'application/json'
            },
        })
        .then((res) => res.json() )
        .then((res) => {
            console.log(res);
            this.props.history.push('/SayDetail');
            Toast.success('成功发布评论',1);
            this.setState({
                selectcomment:'none'
            })
        })
        
        //向动态表中commentnum+1
        this.state.commentnum++
        const commentnumParam={
            commentnum:this.state.commentnum
        } 
        await fetch(`https://www.prebeauty.work/saying/${this.state.sayid}`, {
            method: 'PUT',
            body: JSON.stringify(commentnumParam),
            headers: {
                'Content-Type': 'application/json'
            },
        })
        .then((res) => res.json() )
        .then((res) => {
            console.log(res);
        })

        //评论后重新获取数据刷新评论区
        await axios.get('https://www.prebeauty.work/saycomment/'+this.state.sayid)
    　　　.then((res) => {
            console.log(res.data)
            this.setState({
                commentList:res.data
            })
            console.log(this.state.commentList)
    　　　})
        .catch((err) => {
        　　console.log(err);
        })
    }

    render() { 
        var time=this.state.time;
        var sayDate= moment(parseInt(time)).format('MM-DD HH:mm');
        if(this.state.imgsrc){
            var imgsrc_list = this.state.imgsrc.split(';')
        }

    return (
      <div className="Saydetail">
        {/*导航栏*/}
        <Topbar name="内容" color="#95D2AA" />

        {/*动态内容*/}
        <div className='saydetail-container'>
            <img
                className="userimg"
                src={this.state.confimg}	
                alt='.'
            />
            <div className="userdiv">
                <p className='saydetail-nickname'>{this.state.nickname}</p>
                <p className='saydetail-time'>{sayDate}</p> 
            </div>
                
        </div>
        <div className='saydetail-title'>{this.state.title}</div> 
        <div className='saydetail-content'>{this.state.content}</div> 
        <div className='saydetail-pictures' style={{display:this.state.imgExist}}>
        { 
            (!imgsrc_list) ? null : imgsrc_list.map((item,index)=>{
                return (
                    <img 
                        key={index}
                        src={'https://www.prebeauty.work'+item}	
                        alt='.'
                    />      
                )
            })          
        }     
        </div>
        
        {/*动态内容下的图标 */}
        <div className='saydetail-icon'>
                <i className="iconfont icon-fenxiang" style={{color:'#236E3D',fontSize:'25px',position:'absolute',bottom:'9px',left:'8%'}}></i>
                <p style={{left:'16%'}}>分享</p>
                <i className="iconfont icon-53pinglun-" 
                    style={{color:'#236E3D',fontSize:'20px',position:'absolute',bottom:'9px',left:'40%'}}
                    onClick={localStorage.getItem('token') ? this.showSayComment.bind(this) : () => console.log('请先进行登录！')}
                ></i>
                <p style={{left:'48%'}}>{this.state.commentnum==0?'评论':this.state.commentnum}</p>
                {
                    this.state.selectlike==='yes'
                    ? <i className="iconfont icon-w_aixin" 
                        style={{color:'#236E3D',fontSize:'25px',position:'absolute',bottom:'9px',left:'70%'}}
                        onClick={localStorage.getItem('token') ? this.changeLikeicon.bind(this) : () => console.log('请先进行登录！')}
                    ></i>
                    : <i className="iconfont icon-aixin" 
                        style={{color:'#236E3D',fontSize:'25px',position:'absolute',bottom:'9px',left:'70%'}}
                        onClick={localStorage.getItem('token') ? this.changeLikeicon.bind(this) : () => console.log('请先进行登录！')}
                    ></i>
                }
                <p style={{left:'78%'}}>{this.state.likenum==0?'点赞':this.state.likenum}</p>
        </div>

        {/*分割的div */}
        <div className='saydetail-disparse'></div>
        <div style={{width:'100%',height:'40px',borderBottom:'2px solid #eeeeee'}}>
            <p style={{fontWeight:'bolder',float:'left',marginTop:'10px',marginLeft:'5%'}}>评论 {this.state.commentnum}</p>
            <p style={{fontWeight:'bolder',color:'#888888',float:'right',marginTop:'10px',marginRight:'5%'}}>赞 {this.state.likenum}</p>
        </div>

        {/*评论区 */}
        {
            this.state.commentList.map((item,index)=>{
                return (
                    <div key={index} >
                        <Saycomment name={item.name} time={item.time} content={item.content} likenum={item.likenum} userid={item.userid}/>
                    </div>
                ) 
            })
        }
      
        {/*底部tab */}
        <div style={{width:'100%',height:'40px',position:'fixed',bottom:0,backgroundColor:'#eeeeee'}}>
            <div className='saydetail-tab'>
                <div>
                    <i className="iconfont icon-fenxiang" style={{color:'#236E3D',fontSize:'25px',position:'absolute',bottom:'9px',left:'8%'}}></i>
                    <p style={{left:'16%'}}>分享</p>  
                </div>
                <div onClick={localStorage.getItem('token') ? this.showSayComment.bind(this) : () => console.log('请先进行登录！')}>
                    <i className="iconfont icon-53pinglun-" style={{color:'#236E3D',fontSize:'20px',position:'absolute',bottom:'9px',left:'40%'}}></i>
                    <p style={{left:'48%'}}>{this.state.commentnum==0?'评论':this.state.commentnum}</p>  
                </div>
                <div onClick={this.changeLikeicon.bind(this)}>    
                {
                    this.state.selectlike==='yes'
                    ? <i className="iconfont icon-w_aixin" style={{color:'#236E3D',fontSize:'25px',position:'absolute',bottom:'9px',left:'70%'}}></i>
                    : <i className="iconfont icon-aixin" style={{color:'#236E3D',fontSize:'25px',position:'absolute',bottom:'9px',left:'70%'}}></i>
                }
                    <p style={{left:'78%'}}>{this.state.likenum==0?'点赞':this.state.likenum}</p>
                </div>
               
            </div>
        </div>

        {/*点击评论显示的发布评论窗口*/}
        <div className="saydetail-commenttext" style={{display: this.state.selectcomment}}>
            <div className="saydetail-commenttext-tab"> 
                <p style={{color:'#236E3D',position:'absolute',top:'25px',left:'5%'}} 
                    onClick={()=>{
                        this.setState({
                            selectcomment:'none'
                        })
                        Toast.fail('取消发布评论',1);
                }}>取消</p>
                <p style={{position:'absolute',top:'20px',left:'45%',fontSize:'17px'}}>评论</p>
                <p style={{color:'#236E3D',position:'absolute',top:'25px',right:'5%'}} 
                    onClick={this.uploadcomment.bind(this)}>发表</p>
            </div>
            <textarea 
                placeholder='交流你的看法...' 
                style={{width:'80%',height:'90px',borderRadius:'20px',marginTop:'15px',marginLeft:'5%',padding:'6px 3%'}}
                onChange={(e)=>{
                    this.setState({
                        commentContent:e.target.value 
                    })
                }}
            ></textarea>
        </div>
      </div>
    ) 
  }  
} 

export default SayDetail;